<?php

namespace App\Http\Controllers\AgentAdmin;

use Illuminate\Routing\Controller;
use Vinlon\Laravel\LayAdmin\AdminRole;
use Vinlon\Laravel\LayAdmin\SideBar;
use Vinlon\Laravel\LayAdmin\SideBarCollection;

class MenuController extends Controller
{
    /** 查询侧边栏菜单数据 */
    public function sidebar()
    {
        $allMenu = $this->getAgentAdminSidebar();

        return $allMenu->toArray();
    }

    /** 查询菜单列表（树形结构） */
    public function getMenuTree()
    {
        $allMenus = $this->getAgentAdminSidebar();

        return $allMenus->map(function (SideBar $sideBar) {
            $row = [
                'title' => $sideBar->title,
                'id' => $sideBar->uniqId,
                'spread' => true,
                'children' => [],
            ];

            /** @var SideBar $sub */
            foreach ($sideBar->children as $sub) {
                $row['children'][] = [
                    'title' => $sub->title,
                    'id' => $sub->uniqId,
                ];
            }

            return $row;
        })->toArray();
    }

    private function filterRoleMenu($menus, AdminRole $role)
    {
        $roleMenu = new SideBarCollection();

        /** @var SideBar $menu */
        foreach ($menus as $menu) {
            if ($menu->children->count() > 0) {
                $menu->children = $this->filterRoleMenu($menu->children, $role);
                if ($menu->children->count() > 0) {
                    $roleMenu->add($menu);
                }
            } else {
                if (in_array($menu->uniqId, $role->getMenuIds())) {
                    $roleMenu->add($menu);
                }
            }
        }

        return $roleMenu;
    }

    private function getAgentAdminSidebar()
    {
        $sidebarConfig = config('lay-agent-admin.sidebars');
        $sidebars = new SideBarCollection([]);
        foreach ($sidebarConfig as $item) {
            $sidebars->add(SideBar::fromArray($item));
        }

        return $sidebars;
    }
}
